package com.sztle.admodule.control.manager;

import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.huawei.hms.ads.identifier.AdvertisingIdClient;
import com.sztle.admodule.GmAdManager;
import com.sztle.admodule.bean.AdConfigInfo;
import com.sztle.admodule.bean.AdDataInfo;
import com.sztle.admodule.bean.AdReportInfo;
import com.sztle.admodule.bean.ArrivedBackUpEvent;
import com.sztle.admodule.bean.BackUpEvent;
import com.sztle.admodule.bean.PreRiskBean;
import com.sztle.admodule.bean.RuleEvent;
import com.sztle.admodule.bean.RuleItem;
import com.sztle.admodule.bean.SzHitAppInfo;
import com.sztle.admodule.apiprocessor.OutCommProcessor;
import com.sztle.admodule.outstatus.AppStatusProcessor;
import com.sztle.admodule.someutils.AppUtils;
import com.sztle.admodule.someutils.DebugPrint;
import com.sztle.admodule.someutils.SPUtils;
import com.sztle.admodule.someutils.ThreadUtils;
import com.sztle.admodule.someutils.Utils;
import com.sztle.admodule.resp.IResponseCallback;
import com.sztle.admodule.resp.RequestUtils;
import com.sztle.admodule.resp.ServiceHelper;
import com.sztle.admodule.resp.api.RiskControlApi;
import com.sztle.admodule.resp.base.AdBaseResponse;
import com.sztle.admodule.control.AppInfoManager;
import com.sztle.admodule.control.event.SzAdEvents;
import com.sztle.admodule.control.event.SzTrackEvents;
import com.sztle.admodule.control.input.SzInEventParam;
import com.sztle.admodule.control.input.SzInHitAppParam;
import com.sztle.admodule.control.input.SzInPackageInfo;
import com.sztle.admodule.control.input.SzInRiskDeviceParam;
import com.sztle.admodule.control.oaid.IOaidListener;
import com.sztle.admodule.control.oaid.OaidUtils;
import com.sztle.admodule.control.output.SzOutPrePrivacyConfig;
import com.sztle.admodule.control.output.SzOutRiskHitDeviceResult;
import com.sztle.admodule.control.utils.HashUtils;
import com.sztle.admodule.control.utils.UserDeviceUtils;
import com.sztle.admodule.myutils.GlobalAppUtils;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.listener.OnGetOaidListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ControlManager {
    private static final String TAG = "RiskInfoLog";

    private static String originOaid = "";
    private static String convertOaid = "";
    private static final String keyOriginId = "keyOriginId";
    private static final String KEY_ID_FROM = "myidfrom";
    private static final String keyPreConfig = "keyPreConfig";
    private static final String keyFirstStartApp = "keyFirstStartApp";

    public final static int OAID_FROM_XTY = 0;
    public final static int OAID_FROM_UM = 1;
    public final static int OAID_FROM_JINHON = 2;
    public final static int OAID_FROM_ADSPARK = 3;

    private static SparseArray<Boolean> sGetOaidList = new SparseArray<>();

    private static SparseArray<String> sOaidTypeName = new SparseArray<>();

    private static SzOutPrePrivacyConfig sPrePrivacyConfig;
    private static SzOutRiskHitDeviceResult sRiskHitDeviceResult;
    private static SzHitAppInfo sHitAppInfo = new SzHitAppInfo();

    private static boolean isFinalSetOpen = false;//是否最终决定开关了
    private static boolean isStartGetRisk = false;//是否获取到了后端归因风控结果
    private static boolean isStartRiskTask = false;//是否开启了风控任务。
    private static boolean isAdjustAttribute = false;

    public static boolean isAdjustAttribute() {
        if (sPrePrivacyConfig != null && sPrePrivacyConfig.audit) {
            return true;
        }
        return isAdjustAttribute;
    }

    public static void setOpen(boolean open, boolean isFinal, String msg) {
        if (isFinalSetOpen) {
            return;
        }
        if (isFinal) {
            DebugPrint.d(TAG, "信息：" + msg + ",开关：" + open);
            ControlManager.reportAppLog(SzTrackEvents.u_final_risk_msg, msg + ",ad open:" + (open ? "open" : "close"));
            isFinalSetOpen = true;
        }
        GmAdManager.setUseAdExp(open, msg);
    }

    public static void setOpen(boolean open, String msg) {
        DebugPrint.d(TAG, "信息：" + msg + ",开关：" + open);
        if (GmAdManager.isUseAdExp() != open || !GmAdManager.getLastMsg().equalsIgnoreCase(msg)) {
            ControlManager.reportAppLog(SzTrackEvents.u_final_risk_msg, msg + ",ad open:" + (open ? "open" : "close"));
        }

        isFinalSetOpen = true;
        GmAdManager.setUseAdExp(open, msg);
    }

    public static boolean isFinalAdjustOpen() {
        return isFinalSetOpen && isAdjustAttribute;
    }

    public static void init(Application application) {
        if (application == null) {
            return;
        }
        Utils.init(application);
        GlobalAppUtils.initApp(application);
        if (SPUtils.getInstance().getLong(keyFirstStartApp, 0L) == 0) {
            SPUtils.getInstance().put(keyFirstStartApp, System.currentTimeMillis());
        }
        UserDeviceUtils.registerBatteryChangeListener(application);
        if (OutCommProcessor.isFirstEnterApp()) {
            reportAppLog(SzTrackEvents.app_start);
        }

        UMengManager.initPreUm();
        OaidUtils.init();
        resetFlag();
        AppInfoManager.setHomeActivityExist(false);
        startExecutePreConfig();
    }

    private static void resetFlag() {
        isStartGetRisk = false;
        isStartRiskTask = false;
    }

    static {
        sGetOaidList.put(OAID_FROM_XTY, false);
        sGetOaidList.put(OAID_FROM_UM, false);
        sGetOaidList.put(OAID_FROM_JINHON, false);

        sOaidTypeName.put(OAID_FROM_XTY, "信通院");
        sOaidTypeName.put(OAID_FROM_UM, "友盟");
        sOaidTypeName.put(OAID_FROM_JINHON, "鲸鸿");
        sOaidTypeName.put(OAID_FROM_ADSPARK, "adspark");
    }

    public static String getOriginOaid() {
        if (!TextUtils.isEmpty(originOaid)) {
            return originOaid;
        }
        return SPUtils.getInstance().getString(keyOriginId);
    }

    public static String getSSOaid() {
        return convertOaid;
    }

    //第一步获取隐私前
    public static void startExecutePreConfig() {
        getPrePrivacyConfig(new IResponseCallback<AdBaseResponse<SzOutPrePrivacyConfig>>() {
            @Override
            public void onSuccess(AdBaseResponse<SzOutPrePrivacyConfig> data) {
                if (data != null) {
                    sPrePrivacyConfig = data.data;
                    if (sPrePrivacyConfig != null) {
                        Gson gson = new Gson();
                        String save = gson.toJson(sPrePrivacyConfig);
                        SPUtils.getInstance().put(keyPreConfig, save);
                    }
                    if (AppStatusProcessor.isDebug()) {
                        sPrePrivacyConfig.sdk = true;
                        sPrePrivacyConfig.audit = false;
                        sPrePrivacyConfig.singleSplash = false;
                        sPrePrivacyConfig.singleHotSplash = false;
                    }

                    processPreConfig(false);
                    preConfigResultCode = 1;
                }
            }

            @Override
            public void onFail(String failMessage) {
                String save = SPUtils.getInstance().getString(keyPreConfig, "");
                if (!TextUtils.isEmpty(save)) {
                    Gson gson = new Gson();
                    sPrePrivacyConfig = gson.fromJson(save, SzOutPrePrivacyConfig.class);

                    if (AppStatusProcessor.isDebug()) {
                        sPrePrivacyConfig.sdk = true;
                        sPrePrivacyConfig.audit = false;
                    }

                }

                processPreConfig(true);
                preConfigResultCode = 2;
            }
        });
    }


    public static void processRiskResult() {
        DebugPrint.d(TAG, "开始 processRiskResult");
        if (sRiskHitDeviceResult == null) {
            return;
        }
        if (sRiskHitDeviceResult.riskHit) {
            setOpen(false, "风控项命中:" + sRiskHitDeviceResult.riskIndex);
        } else {
            setOpen(true, "风控项未命中");
        }
    }

    public static boolean canStartInitSdk() {
        if (AppInfoManager.isUserAgree()) {
            return true;
        }
        if (sPrePrivacyConfig == null) {
            return false;
        }
        if (UserDeviceUtils.isGMore()) {
            return false;
        }
        if (sPrePrivacyConfig.audit || !sPrePrivacyConfig.sdk) {
            //不可前置sdk
            return false;
        }
        //todo  可新增条件
        if (openFromLocal()) {
            return false;
        }
        return true;
    }

    public static void processPreConfig(boolean isSave) {
        DebugPrint.d(TAG, "开始processPreConfig");
        if (sPrePrivacyConfig == null) {
            return;
        }
        if (sHitAppInfo == null) {
            sHitAppInfo = new SzHitAppInfo();
        }
        sHitAppInfo.isCheck = true;

        List<String> hitApp = new ArrayList<>();
        if (sPrePrivacyConfig.appList != null && !sPrePrivacyConfig.appList.isEmpty()) {
            for (String packageName : sPrePrivacyConfig.appList) {
                if (AppUtils.isAppInstalled(packageName)) {
                    hitApp.add(packageName);
                }
            }
        }
        if (!hitApp.isEmpty()) {
            sHitAppInfo.isHitApp = true;
            sHitAppInfo.hitAppList.addAll(hitApp);
        }
        if (sPrePrivacyConfig.audit) {
            GmAdManager.setForbidSdkMode(true);
            setOpen(false, true, "审核模式");
            GmAdManager.setLocalAdExp(false);
            return;
        }
//        if (!sPrePrivacyConfig.sdk) {
//            AdManager.setForbidSdkMode(true);
//            setOpen(false, true, "击中前置黑名单");
//            return;
//        }

        if (!hitApp.isEmpty()) {
            GmAdManager.setForbidSdkMode(true);
            setOpen(false, true, "非审核模式击中应用");
            GmAdManager.setLocalAdExp(false);
            return;
        }
        //到这里表明可以前置
        GmAdManager.setForbidSdkMode(false);
        if (sPrePrivacyConfig.sdk) {
            if (checkLocalCode < 1) {
                checkLocalDevice();
            }
        }


//        if (checkLocalCode < 1) {
//            checkLocalDevice();
//        }

    }

    private static void checkLocalDevice() {
        if (checkLocalCode >= 2) {
            return;
        }
        if (openFromLocal()) {
            setOpen(false, false, "击中本地默认配置风险项");
            GmAdManager.setLocalAdExp(false);
        } else {
            setOpen(true, false, "未击中本地默认配置风险项");
        }
    }

    //不断check 击中
    public static void checkHitApp() {
        if (UserDeviceUtils.isGMore()) {
            return;
        }
        if (sHitAppInfo == null) {
            return;
        }
        if (!sHitAppInfo.isCheck) {
            //还没进行检测完
            return;
        }
        if (!sHitAppInfo.isHitApp) {
            //没有命中应用
            return;
        }
        if (sHitAppInfo.hitAppList.isEmpty()) {
            //命中应用为空
            return;
        }
        if (sHitAppInfo.isReport) {
            //已经上报过乐
            return;
        }
        //进行上报
        sHitAppInfo.isReport = true;
        hitTargetApp(sHitAppInfo.hitAppList.get(0), new IResponseCallback<AdBaseResponse<String>>() {
            @Override
            public void onSuccess(AdBaseResponse<String> data) {
                sHitAppInfo.isReport = true;
            }

            @Override
            public void onFail(String failMessage) {
                sHitAppInfo.isReport = false;
            }
        });
    }


    //隐私前配置状态码
    private static int preConfigResultCode = 0;

    public static boolean isGetPreConfig() {
        return preConfigResultCode > 0;
    }

    public static boolean isPreConfigSuccess() {
        return preConfigResultCode == 1;
    }

    public static boolean isPreConfigFail() {
        return preConfigResultCode == 2;
    }

    //隐私前获取基本信息
    private static void getPrePrivacyConfig(IResponseCallback<AdBaseResponse<SzOutPrePrivacyConfig>> callback) {
        SzInPackageInfo packageInfo = new SzInPackageInfo();
        packageInfo.pkg = AppUtils.getAppPackageName();
        packageInfo.version = AppUtils.getAppVersionName();
        ServiceHelper.getService(RiskControlApi.class).getPrePrivacyConfig(RequestUtils.getSzHeadMap(), RequestUtils.getRequestObjectBody(packageInfo)).enqueue(new Callback<AdBaseResponse<SzOutPrePrivacyConfig>>() {
            @Override
            public void onResponse(Call<AdBaseResponse<SzOutPrePrivacyConfig>> call, Response<AdBaseResponse<SzOutPrePrivacyConfig>> response) {

                if (response.isSuccessful() && response.body() != null && response.body().code == AdBaseResponse.SUCCESS) {
                    AdBaseResponse<SzOutPrePrivacyConfig> body = response.body();
                    if (callback != null) {
                        callback.onSuccess(body);
                    }
                    return;
                }
                if (callback != null) {
                    callback.onFail(response.body() != null ? response.body().msg : "not success");
                }
            }

            @Override
            public void onFailure(Call<AdBaseResponse<SzOutPrePrivacyConfig>> call, Throwable t) {
                if (callback != null) {
                    callback.onFail(t.getCause() + t.getMessage());
                }
            }
        });
    }

    //击中应用
    public static void hitTargetApp(String hitAppPkgName, IResponseCallback<AdBaseResponse<String>> callback) {
        if (TextUtils.isEmpty(hitAppPkgName)) {
            callback.onFail("hitAppPkgName is empty");
            return;
        }
        SzInHitAppParam hitAppParam = new SzInHitAppParam();
        hitAppParam.appPkg = hitAppPkgName;
        hitAppParam.pkg = AppUtils.getAppPackageName();
        hitAppParam.version = AppUtils.getAppVersionName();
        hitAppParam.ssoaid = getSSOaid();
        hitAppParam.deviceId = UserDeviceUtils.getUUId();
        hitAppParam.oaid = getOriginOaid();
        hitAppParam.brand = Build.BRAND;
        hitAppParam.model = Build.MODEL;
        hitAppParam.osversion = Build.VERSION.RELEASE;
        hitAppParam.androidid = UserDeviceUtils.getAndroidId();
        ServiceHelper.getService(RiskControlApi.class).hitTargetApp(RequestUtils.getSzHeadMap(), RequestUtils.getRequestObjectBody(hitAppParam)).enqueue(new Callback<AdBaseResponse<String>>() {
            @Override
            public void onResponse(Call<AdBaseResponse<String>> call, Response<AdBaseResponse<String>> response) {

                if (response.isSuccessful() && response.body() != null && response.body().code == AdBaseResponse.SUCCESS) {
                    AdBaseResponse<String> body = response.body();
                    if (callback != null) {
                        callback.onSuccess(body);
                    }
                    return;
                }
                if (callback != null) {
                    callback.onFail(response.body() != null ? response.body().msg : "not success");
                }
            }

            @Override
            public void onFailure(Call<AdBaseResponse<String>> call, Throwable t) {
                if (callback != null) {
                    callback.onFail(t.getCause() + t.getMessage());
                }
            }
        });
    }


    private static boolean checkGetOaid() {
        String save = SPUtils.getInstance().getString(keyOriginId, "");
        if (TextUtils.isEmpty(save)) {
            return false;
        }
        if (save.replace("-", "").startsWith("00000000") && save.replace("-", "").endsWith("000000")) {
            return false;
        }
        return true;
    }


    public static void setOaidAndStartRiskTask(String oaid, int type) {
        sGetOaidList.put(type, true);
        boolean isGoNext = false;
        if (TextUtils.isEmpty(oaid) || oaid.replace("-", "").startsWith("000000000")) {
            if (sGetOaidList.get(OAID_FROM_XTY) && sGetOaidList.get(OAID_FROM_UM)) {
                isGoNext = UserDeviceUtils.isHuaWei() ? sGetOaidList.get(OAID_FROM_JINHON) : true;
            } else {
                isGoNext = false;
            }
        } else {
            isGoNext = true;
            originOaid = oaid;
            SPUtils.getInstance().put(keyOriginId, oaid);
            SPUtils.getInstance().put(KEY_ID_FROM, type);
            String name = sOaidTypeName.get(type);
            // reportAppLog(SzTrackEvents.oaid_get_success, name);
            if (TextUtils.isEmpty(convertOaid)) {
                convertOaid = HashUtils.hashAndEncode(oaid);
            }
        }
        if (!isGoNext) {
            return;
        }
        ThreadUtils.runOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                startExecuteRiskOpen();
            }
        }, 100);

    }

    //进入loading页开始
    public static void startRiskTask() {
        if (UserDeviceUtils.isGMore()) {
            isStartRiskTask = true;
            return;
        }
        if (isStartRiskTask) {
            return;
        }
        isStartRiskTask = true;
        checkLocalDevice();
        if (checkGetOaid()) {
            originOaid = SPUtils.getInstance().getString(keyOriginId);
            if (TextUtils.isEmpty(convertOaid)) {
                convertOaid = HashUtils.hashAndEncode(originOaid);
            }
            int type = SPUtils.getInstance().getInt(KEY_ID_FROM, -1);
            if (type >= OAID_FROM_XTY && type <= OAID_FROM_ADSPARK) {
                String name = sOaidTypeName.get(type);
                // reportAppLog(SzTrackEvents.oaid_get_success, name);
            }

            ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    startExecuteRiskOpen();
                }
            }, 100);
            return;
        }

        //常用的信通院获取
        OaidUtils.getOfficialOaid(new IOaidListener() {
            @Override
            public void onGetResult(String oaid) {
                setOaidAndStartRiskTask(oaid, OAID_FROM_XTY);
            }
        });


        //华为鲸宏获取
        if (UserDeviceUtils.isHuaWei()) {
            ThreadUtils.executeByCpu(new ThreadUtils.SimpleTask<String>() {
                @Override
                public String doInBackground() throws Throwable {
                    String result = "";
                    try {
                        AdvertisingIdClient.Info info = AdvertisingIdClient.getAdvertisingIdInfo(Utils.getApp());
                        if (null != info) {
                            result = info.getId();
                        }
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                    return result;
                }

                @Override
                public void onSuccess(String result) {
                    setOaidAndStartRiskTask(result, OAID_FROM_JINHON);
                }
            });
        }

        //友盟获取
        UMConfigure.getOaid(Utils.getApp(), new OnGetOaidListener() {
            @Override
            public void onGetOaid(String result) {
                setOaidAndStartRiskTask(result, OAID_FROM_UM);
            }
        });
    }

    private static int msg_query_risk = 1;
    private static Handler sQueryHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == msg_query_risk) {
                queryRisk();
            }
        }
    };

    //第二步开始风控击中
    public static void startExecuteRiskOpen() {
        if (isStartGetRisk) {
            return;
        }
        isStartGetRisk = true;
        queryRisk();
    }

    public static void cancelExecuteRiskOpen() {
        sQueryHandler.removeCallbacksAndMessages(null);
        DebugPrint.d(TAG + "queryRisk", "queryRisk 查询中 取消");
    }

    private static String lastRiskResult = "";

    private static long lastQueryTime = 0;

    public static void justQuerySingleRisk() {
        if (System.currentTimeMillis() - lastQueryTime < 200) {
            return;
        }
        lastQueryTime = System.currentTimeMillis();
        getRiskOpen(new IResponseCallback<AdBaseResponse<SzOutRiskHitDeviceResult>>() {
            @Override
            public void onSuccess(AdBaseResponse<SzOutRiskHitDeviceResult> data) {
                DebugPrint.d(TAG, "startExecuteRiskOpen 成功");
                if (data != null && data.data != null) {
                    sRiskHitDeviceResult = data.data;
                    if (!TextUtils.equals(lastRiskResult, sRiskHitDeviceResult.toString())) {
                        reportAppLog(SzTrackEvents.u_risk_rest, sRiskHitDeviceResult.toString());
                        lastRiskResult = sRiskHitDeviceResult.toString();
                    }

                }
                if (sRiskHitDeviceResult != null && !TextUtils.isEmpty(sRiskHitDeviceResult.attribute) && !sRiskHitDeviceResult.attribute.equalsIgnoreCase("0")) {
                    DebugPrint.d(TAG + "queryRisk", "已经归因，停止:value:" + sRiskHitDeviceResult.attribute);
                    cancelExecuteRiskOpen();
                    isAdjustAttribute = true;
                }
                processRiskResult();
            }

            @Override
            public void onFail(String failMessage) {
                DebugPrint.d(TAG, "startExecuteRiskOpen 失败：" + failMessage);
            }
        });
    }

    private static void queryRisk() {
        DebugPrint.d(TAG + "queryRisk", "queryRisk 查询中----");
        if (TextUtils.isEmpty(convertOaid)) {
            convertOaid = HashUtils.hashAndEncode(originOaid);
        }
        if (AppInfoManager.isHomeActivityExist()) {
            cancelExecuteRiskOpen();
            return;
        }
        DebugPrint.d(TAG, "开始 startExecuteRiskOpen isMainThread = " + ThreadUtils.isMainThread());
        getRiskOpen(new IResponseCallback<AdBaseResponse<SzOutRiskHitDeviceResult>>() {
            @Override
            public void onSuccess(AdBaseResponse<SzOutRiskHitDeviceResult> data) {
                DebugPrint.d(TAG, "startExecuteRiskOpen 成功");
                if (data != null && data.data != null) {
                    sRiskHitDeviceResult = data.data;
                    if (!TextUtils.equals(lastRiskResult, sRiskHitDeviceResult.toString())) {
                        reportAppLog(SzTrackEvents.u_risk_rest, sRiskHitDeviceResult.toString());
                        lastRiskResult = sRiskHitDeviceResult.toString();
                    }

                }
                if (sRiskHitDeviceResult != null && !TextUtils.isEmpty(sRiskHitDeviceResult.attribute) && !sRiskHitDeviceResult.attribute.equalsIgnoreCase("0")) {
                    DebugPrint.d(TAG + "queryRisk", "已经归因，停止:value:" + sRiskHitDeviceResult.attribute);
                    cancelExecuteRiskOpen();
                    isAdjustAttribute = true;
                } else {
                    DebugPrint.d(TAG + "queryRisk", "未归因，继续 value:" + sRiskHitDeviceResult.attribute);
                    sQueryHandler.sendEmptyMessageDelayed(msg_query_risk, 500);
                }
                processRiskResult();
            }

            @Override
            public void onFail(String failMessage) {
                sQueryHandler.sendEmptyMessageDelayed(msg_query_risk, 500);
                DebugPrint.d(TAG, "startExecuteRiskOpen 失败：" + failMessage);
            }
        });
    }

//    private static List<String> blackAppList = Arrays.asList("com.service.android.gov.cn", "com.gov.cn", "com.hanweb.android.jtysb.jmportal.activity",
//            "cn.gov.mca", "com.leimingtech.sifaburnapp", "com.hanweb.zrzyb.android.activity", "com.uknower.satapp", "cn.gov.mofcom.android",
//            "com.ccdi.news", "cn.gov.customs.zshg", "com.zhiwang.site.s47933", "com.zrar.qghlwpt", "com.hanweb.android.gdxx.jmportal.activity",
//            "com.hanweb.android.tyzj.activity", "cn.android.sia.exitentrypermit", "com.hanweb.TLJGZ.activity", "com.chinamobile.mcloud.peoplenewscloud",
//            "com.hanweb.android.zhejiang.activity", "com.hanweb.android.jszwfw.activity", "com.systoon.beijingtoon", "mobi.w3studio.apps.android.shsmy.phone",
//            "com.hanweb.ganfutong", "com.digitalgd.dgyss", "com.teamtalk.im", "com.github.uiautomator", "com.github.uiautomator.test", "com.oppo.cloudtest.androidagent", "com.vivo.autotest.screen_record");

    private static List<String> blackAppList = Arrays.asList("com.github.uiautomator", "com.github.uiautomator.test", "com.oppo.cloudtest.androidagent", "de.robv.android.xposed.installer", "org.autojs.autojs", "com.cyjh.mobileanjian.vip", "com.topjohnwu.magisk", "com.guoshi.httpcanany", "com.huawei.deveco.assistant", "com.huawei.deveco.apptest.plrdtest", "com.vivo.autotest.screen_record", "io.appium.unlock", "com.my.idchanger");
    private static int checkLocalCode = 0;


//    一级：root、虚拟机、隐私协议打开、proxy代理
//
//    二级：开发者模式、sim、VPN、usb、常亮

    private static boolean openFromLocal() {
        SzInRiskDeviceParam riskDeviceParam = getRiskDeviceParam();
        checkLocalCode = 1;
        if (sPrePrivacyConfig == null || sPrePrivacyConfig.indexList == null || sPrePrivacyConfig.indexList.isEmpty()) {
            Log.i("NewRiskInfoLog", "未获取到默认配置，走写死的本地项风控");
            if (riskDeviceParam.getFirstLocalRiskResult()) {
                //一级
                Log.i("NewRiskInfoLog", "未获取到默认配置，命中写死的本地项风控");
                return true;
            }
            if (riskDeviceParam.getSecondLocalRiskCount() >= 2) {
                //二级
                return true;
            }
            for (String packageName : blackAppList) {
                if (AppUtils.isAppInstalled(packageName)) {
                    Log.i("NewRiskInfoLog", "未获取到默认配置，命中写死的本地项的应用列表");
                    return true;
                }
            }
            return false;
        }
        checkLocalCode = 2;
        Log.i("NewRiskInfoLog", "获取到默认配置，开始匹配本地设备项");
        List<String> checkKeyList = riskDeviceParam.getInRiskKey();
        for (PreRiskBean bean : sPrePrivacyConfig.indexList) {
            if (bean.code.equalsIgnoreCase("brand") && !TextUtils.isEmpty(bean.val)) {
                List<String> branList = Arrays.stream(bean.val.split(",")).collect(Collectors.toList());
                if (branList.contains(riskDeviceParam.brand)) {
                    Log.i("NewRiskInfoLog", "获取到默认配置，匹配本地设备项，命中品牌");
                    return true;
                }
                continue;
            }
            if (bean.level == 1 && bean.status != 0 && checkKeyList.contains(bean.code)) {
                Log.i("NewRiskInfoLog", "获取到默认配置，匹配本地设备项，命中本地项：" + bean.code);
                return true;
            }
        }
        Log.i("NewRiskInfoLog", "获取到默认配置，匹配本地设备项，未命中本地项");
        return false;
    }

    private static SzInRiskDeviceParam getRiskDeviceParam() {
        SzInRiskDeviceParam deviceParam = new SzInRiskDeviceParam();
        deviceParam.pkg = AppUtils.getAppPackageName();
        deviceParam.ssoaid = getSSOaid();
        deviceParam.deviceId = UserDeviceUtils.getUUId();
        deviceParam.oaid = getOriginOaid();
        deviceParam.brand = Build.BRAND;
        deviceParam.model = Build.MODEL;
        deviceParam.version = AppUtils.getAppVersionName();
        deviceParam.osversion = Build.VERSION.RELEASE;
        deviceParam.androidid = UserDeviceUtils.getAndroidId();

        deviceParam.simStatus = UserDeviceUtils.isNoSim() ? "1" : "0";
        deviceParam.clStatus = UserDeviceUtils.isAlwaysScreenOn() ? "1" : "0";
        deviceParam.developerStatus = UserDeviceUtils.isDevelopSet() ? "1" : "0";
        deviceParam.rootStatus = UserDeviceUtils.isRootDevice() ? "1" : "0";
        deviceParam.usbStatus = UserDeviceUtils.isUsbPlugin() ? "1" : "0";
        deviceParam.chargeStatus = UserDeviceUtils.isCharging() ? "1" : "0";
        deviceParam.electricityStatus = UserDeviceUtils.isElectricityStatus() ? "1" : "0";
        deviceParam.rootStatus = UserDeviceUtils.isRootDevice() ? "1" : "0";
        deviceParam.emulatorStatus = UserDeviceUtils.isEmulator() ? "1" : "0";
        deviceParam.proxyStatus = UserDeviceUtils.isWifiProxy() ? "1" : "0";
        deviceParam.volumeStatus = UserDeviceUtils.isVolumeStatus() ? "1" : "0";
        deviceParam.gyroscopeStatus = UserDeviceUtils.hasGravitySensor() ? "0" : "1";
        deviceParam.vpnStatus = UserDeviceUtils.isVpn() ? "1" : "0";
        deviceParam.brightnessStatus = UserDeviceUtils.isBrightnessBad() ? "1" : "0";
        deviceParam.privacyAgreementBottomStatus = AppStatusProcessor.isPrivacyScrollBottom() ? "1" : "0";
        deviceParam.privacyAgreementOpenStatus = AppStatusProcessor.isPrivacyScroll() ? "1" : "0";

        boolean isRecord = SPUtils.getInstance().getBoolean("isRecord", false);
        deviceParam.screenRecordingStatus = isRecord ? "1" : "0";
        // 获取蓝牙开关状态
        deviceParam.bluetoothStatus = isBluetoothEnabled() ? "1" : "0";
        return deviceParam;
    }

    public static boolean isBluetoothEnabled() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
            return bluetoothAdapter.isEnabled();
        }
        return false;
    }

    //获取风控设备项击中结果
    private static String lastRiskParam = "";

    public static void getRiskOpen(IResponseCallback<AdBaseResponse<SzOutRiskHitDeviceResult>> callback) {

        SzInRiskDeviceParam deviceParam = getRiskDeviceParam();
        if (!TextUtils.equals(lastRiskParam, deviceParam.toString())) {
            reportAppLog(SzTrackEvents.u_risk_req, deviceParam.toString());
            lastRiskParam = deviceParam.toString();
        }

        DebugPrint.d(TAG, "deviceParam ==== " + deviceParam);
//        Toaster.showLong("usb:"+deviceParam.usbStatus+",dev:"+deviceParam.developerStatus);
        ServiceHelper.getService(RiskControlApi.class).getRiskAdjustResult(RequestUtils.getSzHeadMap(), RequestUtils.getRequestObjectBody(deviceParam)).enqueue(new Callback<AdBaseResponse<SzOutRiskHitDeviceResult>>() {
            @Override
            public void onResponse(Call<AdBaseResponse<SzOutRiskHitDeviceResult>> call, Response<AdBaseResponse<SzOutRiskHitDeviceResult>> response) {
                DebugPrint.d(TAG, "getRiskOpen onResponse");
                if (response.isSuccessful() && response.body() != null && response.body().code == AdBaseResponse.SUCCESS) {
                    AdBaseResponse<SzOutRiskHitDeviceResult> body = response.body();
                    if (callback != null) {
                        callback.onSuccess(body);
                    }
                    return;
                }
                if (callback != null) {
                    callback.onFail(response.body() != null ? response.body().msg : "not success");
                }
            }

            @Override
            public void onFailure(Call<AdBaseResponse<SzOutRiskHitDeviceResult>> call, Throwable t) {
                DebugPrint.d(TAG, "getRiskOpen onFailure");
                if (callback != null) {
                    callback.onFail(t.getCause() + t.getMessage());
                }
            }
        });
    }

    public static void reportCommLog(String eventName, String logType, Object object) {
        if (TextUtils.isEmpty(eventName) || TextUtils.isEmpty(logType)) {
            return;
        }
        DebugPrint.d(TAG, "eventName = " + eventName);
        if (logType.equalsIgnoreCase("0")) {
        }
        SzInEventParam param;
        if (object instanceof String) {
            param = new SzInEventParam(eventName, logType, (String) object);
        } else {
            param = new SzInEventParam(eventName, logType, object);
        }

        ServiceHelper.getService(RiskControlApi.class).reportCommLog(RequestUtils.getSzLogHeadMap(), RequestUtils.getRequestObjectBody(param)).enqueue(new Callback<AdBaseResponse<String>>() {

            @Override
            public void onResponse(Call<AdBaseResponse<String>> call, Response<AdBaseResponse<String>> response) {
                DebugPrint.d(TAG, "reportCommLog success");
            }

            @Override
            public void onFailure(Call<AdBaseResponse<String>> call, Throwable t) {
                DebugPrint.d(TAG, "reportCommLog fail");
            }
        });
    }

    public static void reportAppLog(String eventName, String param) {
        reportCommLog(eventName, "0", param);
    }

    public static void reportAppLog(String eventName) {
        reportCommLog(eventName, "0", null);
    }

    public static void feedbackMsg(String msg) {
        reportCommLog("FeedUsEvent", "0", "msg");
    }

    public static void reportAdLog(String eventName, AdReportInfo reportInfo) {
        if (eventName.contains("ad_show")) {
            if (eventName.equalsIgnoreCase(SzAdEvents.show_splash_1) || eventName.equalsIgnoreCase(SzAdEvents.show_splash_2)) {
                DebugPrint.d(TAG, "feedbackEvent 触发开屏展示");
                triggerRuleEvent(TYPE_AD_SPLASH, Math.round(Float.parseFloat(reportInfo.ecpm)));
            } else if (eventName.equalsIgnoreCase(SzAdEvents.show_int_1) || eventName.equalsIgnoreCase(SzAdEvents.show_int_2)) {
                DebugPrint.d(TAG, "feedbackEvent 触发插屏展示");
                triggerRuleEvent(TYPE_AD_INT, Math.round(Float.parseFloat(reportInfo.ecpm)));
            } else if (eventName.equalsIgnoreCase(SzAdEvents.show_reward)) {
                DebugPrint.d(TAG, "feedbackEvent 触发激励展示");
                triggerRuleEvent(TYPE_AD_REWARD, Math.round(Float.parseFloat(reportInfo.ecpm)));
            } else if (eventName.equalsIgnoreCase(SzAdEvents.show_native) || eventName.equalsIgnoreCase(SzAdEvents.show_native_2)) {
                DebugPrint.d(TAG, "feedbackEvent 触发信息流展示");
                triggerRuleEvent(TYPE_AD_NATIVE, Math.round(Float.parseFloat(reportInfo.ecpm)));
            }
        }
        reportCommLog(eventName, "1", reportInfo);
    }


    public interface IReportEventCallback {
        void onReportSuccess();
    }

    private static Map<String, Boolean> sMapReportingEvent = new HashMap<>();

    //事件达成上报
    public static void reportEvent(BackUpEvent upEvent, IReportEventCallback reportEventCallback) {
        if (upEvent == null) {
            return;
        }
        if (sMapReportingEvent.containsKey(upEvent.event) && sMapReportingEvent.get(upEvent.event)) {
            DebugPrint.d(TAG, "feedbackEvent 事件：" + upEvent.event + "正在上报中");
            return;
        }
        sMapReportingEvent.put(upEvent.event, true);
        DebugPrint.d(TAG, "feedbackEvent 事件：" + upEvent.event + "达成上报");
        ServiceHelper.getService(RiskControlApi.class).reportEvent(RequestUtils.getSzLogHeadMap(), RequestUtils.getRequestObjectBody(upEvent)).enqueue(new Callback<AdBaseResponse<String>>() {

            @Override
            public void onResponse(Call<AdBaseResponse<String>> call, Response<AdBaseResponse<String>> response) {
                DebugPrint.d(TAG, "feedbackEvent reportEvent success===>" + upEvent.event);
                sMapReportingEvent.put(upEvent.event, false);
                if (response.isSuccessful()) {
                    AdBaseResponse<String> result = response.body();
                    if (result != null && result.code == AdBaseResponse.SUCCESS) {
                        if (reportEventCallback != null) {
                            DebugPrint.d(TAG, "feedbackEvent 事件：" + upEvent.event + "达成上报成功");
                            reportEventCallback.onReportSuccess();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<AdBaseResponse<String>> call, Throwable t) {
                sMapReportingEvent.put(upEvent.event, false);
                DebugPrint.d(TAG, "feedbackEvent 事件：" + upEvent.event + "达成上报失败:" + t.getMessage());
            }
        });
    }

    public static int getHomeIntsCount() {
        if (sPrePrivacyConfig != null) {
            return sPrePrivacyConfig.interstitial;
        }
        return 2;
    }

    public static int getHomeRewardCount() {
        if (sPrePrivacyConfig != null) {
            return sPrePrivacyConfig.reward;
        }
        return 0;
    }

    public static int getTimerInterval() {
        if (sPrePrivacyConfig != null) {
            return sPrePrivacyConfig.time;
        }
        return 12;
    }

    public static boolean isSingleSplash() {
        if (sPrePrivacyConfig != null) {
            return sPrePrivacyConfig.singleSplash;
        }
        return false;
    }

    public static boolean isSingleHotSplash() {
        if (sPrePrivacyConfig != null) {
            return sPrePrivacyConfig.singleHotSplash;
        }
        return false;
    }

    public static boolean isQueryLoopMode() {
        if (sPrePrivacyConfig != null) {
            return sPrePrivacyConfig.attrPolling;
        }
        return false;
    }


    public static void triggerQueryAdjust() {
        if (UserDeviceUtils.isGMore()) {
            return;
        }
        if (sPrePrivacyConfig == null) {
            return;
        }
        if (isAdjustAttribute()) {
            return;
        }
        if (!sPrePrivacyConfig.sdk
                && !AppInfoManager.isUserAgree()) {
            return;
        }
        if (!isQueryLoopMode()) {
            return;
        }
        justQuerySingleRisk();
    }

    public static AdConfigInfo getAdConfigInfo() {
        if (sPrePrivacyConfig != null && sPrePrivacyConfig.adConfigInfo != null) {
            return sPrePrivacyConfig.adConfigInfo;
        }
        return null;
    }

    /***********************************************************************************/
    private static final String keyIntAdInfo = "keyIntAdInfo";
    private static final String keyRewardAdInfo = "keyRewardAdInfo";
    private static final String keySplashAdInfo = "keySplashAdInfo";
    private static final String keyNativeAdInfo = "keyNativeInfo";
    private static final String keyAllAdInfo = "keyAllAdInfo";

    public static final int TYPE_AD_SPLASH = 0;
    public static final int TYPE_AD_INT = 1;
    public static final int TYPE_AD_REWARD = 2;
    public static final int TYPE_AD_NATIVE = 3;
    public static final int TYPE_AD_ALL = 4;

    public static void saveAdInfo(int adType, int ecpm) {
        if (adType == TYPE_AD_SPLASH) {
            String save = SPUtils.getInstance().getString(keySplashAdInfo, "");
            AdDataInfo adDataInfo = new AdDataInfo();
            if (!TextUtils.isEmpty(save)) {
                adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            }
            adDataInfo.sumEcpm += ecpm;
            adDataInfo.ipu += 1;
            adDataInfo.ecpm = ecpm;
            adDataInfo.ecpmList.add(ecpm);
            adDataInfo.lastTime = System.currentTimeMillis();
            SPUtils.getInstance().put(keySplashAdInfo, adDataInfo.toJsonStr());
            DebugPrint.d(TAG, "feedbackEvent 当前开屏数据  === " + adDataInfo.toJsonStr());
        } else if (adType == TYPE_AD_INT) {
            String save = SPUtils.getInstance().getString(keyIntAdInfo, "");
            AdDataInfo adDataInfo = new AdDataInfo();
            if (!TextUtils.isEmpty(save)) {
                adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            }
            adDataInfo.sumEcpm += ecpm;
            adDataInfo.ipu += 1;
            adDataInfo.ecpm = ecpm;
            adDataInfo.ecpmList.add(ecpm);
            adDataInfo.lastTime = System.currentTimeMillis();
            SPUtils.getInstance().put(keyIntAdInfo, adDataInfo.toJsonStr());
            DebugPrint.d(TAG, "feedbackEvent 当前插屏数据  === " + adDataInfo.toJsonStr());
        } else if (adType == TYPE_AD_REWARD) {
            String save = SPUtils.getInstance().getString(keyRewardAdInfo, "");
            AdDataInfo adDataInfo = new AdDataInfo();
            if (!TextUtils.isEmpty(save)) {
                adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            }
            adDataInfo.sumEcpm += ecpm;
            adDataInfo.ipu += 1;
            adDataInfo.ecpm = ecpm;
            adDataInfo.ecpmList.add(ecpm);
            adDataInfo.lastTime = System.currentTimeMillis();
            SPUtils.getInstance().put(keyRewardAdInfo, adDataInfo.toJsonStr());
            DebugPrint.d(TAG, "feedbackEvent 当前激励数据  === " + adDataInfo.toJsonStr());
        } else if (adType == TYPE_AD_NATIVE) {
            String save = SPUtils.getInstance().getString(keyNativeAdInfo, "");
            AdDataInfo adDataInfo = new AdDataInfo();
            if (!TextUtils.isEmpty(save)) {
                adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            }
            adDataInfo.sumEcpm += ecpm;
            adDataInfo.ipu += 1;
            adDataInfo.ecpm = ecpm;
            adDataInfo.ecpmList.add(ecpm);
            adDataInfo.lastTime = System.currentTimeMillis();
            SPUtils.getInstance().put(keyNativeAdInfo, adDataInfo.toJsonStr());
            DebugPrint.d(TAG, "feedbackEvent 当前信息流数据  === " + adDataInfo.toJsonStr());
        }

        String save = SPUtils.getInstance().getString(keyAllAdInfo, "");
        AdDataInfo adDataInfo = new AdDataInfo();
        if (!TextUtils.isEmpty(save)) {
            adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
        }
        adDataInfo.sumEcpm += ecpm;
        adDataInfo.ipu += 1;
        adDataInfo.ecpm = ecpm;
        adDataInfo.ecpmList.add(ecpm);
        adDataInfo.lastTime = System.currentTimeMillis();
        SPUtils.getInstance().put(keyAllAdInfo, adDataInfo.toJsonStr());
        DebugPrint.d(TAG, "feedbackEvent 当前总数据  === " + adDataInfo.toJsonStr());
    }

    public static void triggerRuleEvent(int adType, int ecpm) {
        long current = System.currentTimeMillis();
        long arriveTime = current - SPUtils.getInstance().getLong(keyFirstStartApp, 0);
        if (arriveTime > 24 * 60 * 60 * 1000) {
            DebugPrint.d(TAG, "feedbackEvent triggerRuleEvent 超过首次启动24小时");
            return;
        }
        saveAdInfo(adType, ecpm);

        if (sPrePrivacyConfig == null || sPrePrivacyConfig.upConf == null || sPrePrivacyConfig.upConf.isEmpty()) {
            DebugPrint.d(TAG, "feedbackEvent triggerRuleEvent 配置事件回传为空");
            return;
        }
        DebugPrint.d(TAG, "feedbackEvent triggerRuleEvent 开始检查是否达成");
        for (RuleEvent event : sPrePrivacyConfig.upConf) {
            String arrivedEvent = SPUtils.getInstance().getString(event.event, "");
            if (!TextUtils.isEmpty(arrivedEvent)) {
                //已经达成过了,检查是否上报过
                ArrivedBackUpEvent arrivedBackUpEvent = new Gson().fromJson(arrivedEvent, ArrivedBackUpEvent.class);
                checkReportCommEvent(arrivedBackUpEvent);
                continue;
            }
            //没有达成过
            RuleItem item;
            if ((item = checkRuleEvent(event)) != null) {
                if (TextUtils.equals(event.event, RuleEvent.ACTIVE)) {
                    //激活事件的话直接上报同时存储起来
                    ArrivedBackUpEvent arrivedBackUpEvent = new ArrivedBackUpEvent();
                    arrivedBackUpEvent.backUpEvent = new BackUpEvent(event.event, new Gson().toJson(item), System.currentTimeMillis());
                    SPUtils.getInstance().put(event.event, new Gson().toJson(arrivedBackUpEvent));
                    reportEvent(arrivedBackUpEvent.backUpEvent, new IReportEventCallback() {
                        @Override
                        public void onReportSuccess() {
                            arrivedBackUpEvent.reportTime = System.currentTimeMillis();
                            SPUtils.getInstance().put(event.event, new Gson().toJson(arrivedBackUpEvent));
                        }
                    });
                } else {
                    //非激活事件，存储起来
                    ArrivedBackUpEvent arrivedBackUpEvent = new ArrivedBackUpEvent();
                    arrivedBackUpEvent.backUpEvent = new BackUpEvent(event.event, new Gson().toJson(item), System.currentTimeMillis());
                    SPUtils.getInstance().put(event.event, new Gson().toJson(arrivedBackUpEvent));
                    checkReportCommEvent(arrivedBackUpEvent);
                }
            }
        }

    }

    //检查除了激活外的其他回传事件
    private static void checkReportCommEvent(ArrivedBackUpEvent arrivedEvent) {
        if (arrivedEvent == null) {
            return;
        }
        if (arrivedEvent.reportTime > 0) {
            DebugPrint.d(TAG, "feedbackEvent 事件：" + arrivedEvent.backUpEvent.event + "已经上报过了");
            return;
        }
        //已经达成但没上报过，先检查激活是否达成并上报过并距离激活上报的时间超过3s
        String activeEventJsonStr = SPUtils.getInstance().getString(RuleEvent.ACTIVE, "");
        ArrivedBackUpEvent activeEvent = new Gson().fromJson(activeEventJsonStr, ArrivedBackUpEvent.class);
        if (TextUtils.isEmpty(activeEventJsonStr)
                || activeEvent == null
                || activeEvent.reportTime == 0) {
            if (activeEvent != null) {
                DebugPrint.d(TAG, "feedbackEvent 激活事件达成了未成功上报");
                reportEvent(activeEvent.backUpEvent, new IReportEventCallback() {
                    @Override
                    public void onReportSuccess() {
                        activeEvent.reportTime = System.currentTimeMillis();
                        SPUtils.getInstance().put(activeEvent.backUpEvent.event, new Gson().toJson(activeEvent));
                    }
                });
            }
            //激活没达成，不上报
            return;
        }
        //激活上报过了，那就判断当前时间距离激活达成时间是否大于3s
        if (System.currentTimeMillis() - activeEvent.reportTime < 3000) {
            ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    reportEvent(arrivedEvent.backUpEvent, new IReportEventCallback() {
                        @Override
                        public void onReportSuccess() {
                            arrivedEvent.reportTime = System.currentTimeMillis();
                            SPUtils.getInstance().put(arrivedEvent.backUpEvent.event, new Gson().toJson(arrivedEvent));
                        }
                    });
                }
            }, 3000);
            return;
        }
        //激活达成时间超过3s，上报
        reportEvent(arrivedEvent.backUpEvent, new IReportEventCallback() {
            @Override
            public void onReportSuccess() {
                arrivedEvent.reportTime = System.currentTimeMillis();
                SPUtils.getInstance().put(arrivedEvent.backUpEvent.event, new Gson().toJson(arrivedEvent));
            }
        });
    }

    //检查需达成的事件
    private static RuleItem checkRuleEvent(RuleEvent event) {
        if (event == null) {
            return null;
        }
        if (event.rule == null || event.rule.isEmpty()) {
            return null;
        }
        //任意达成一条就算达成
        for (RuleItem item : event.rule) {
            if (checkRule(item, getAdDataInfoMap())) {
                // SPUtils.getInstance().put(event.event, true);
                DebugPrint.d(TAG, "feedbackEvent 事件：" + event.event + "达成->" + item.toString());
                return item;
            }
        }
        return null;
    }

    private static Map<Integer, AdDataInfo> getAdDataInfoMap() {
        Map<Integer, AdDataInfo> adDataInfoMap = new HashMap<>();
        String save = SPUtils.getInstance().getString(keySplashAdInfo, "");
        if (!TextUtils.isEmpty(save)) {
            AdDataInfo adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            adDataInfoMap.put(TYPE_AD_SPLASH, adDataInfo);
        }
        save = SPUtils.getInstance().getString(keyIntAdInfo, "");
        if (!TextUtils.isEmpty(save)) {
            AdDataInfo adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            adDataInfoMap.put(TYPE_AD_INT, adDataInfo);
        }
        save = SPUtils.getInstance().getString(keyRewardAdInfo, "");
        if (!TextUtils.isEmpty(save)) {
            AdDataInfo adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            adDataInfoMap.put(TYPE_AD_REWARD, adDataInfo);
        }
        save = SPUtils.getInstance().getString(keyNativeAdInfo, "");
        if (!TextUtils.isEmpty(save)) {
            AdDataInfo adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            adDataInfoMap.put(TYPE_AD_NATIVE, adDataInfo);
        }
        save = SPUtils.getInstance().getString(keyAllAdInfo, "");
        if (!TextUtils.isEmpty(save)) {
            AdDataInfo adDataInfo = new Gson().fromJson(save, AdDataInfo.class);
            adDataInfoMap.put(TYPE_AD_ALL, adDataInfo);
        }
        return adDataInfoMap;
    }

    private static boolean checkRule(RuleItem ruleItem, Map<Integer, AdDataInfo> adDataInfoMap) {
        if (ruleItem == null) {
            return false;
        }
        long startTime = SPUtils.getInstance().getLong(keyFirstStartApp, 0L);

        //先看是否超过了规则的时间
        if ((System.currentTimeMillis() - startTime) > ruleItem.time * 60 * 60 * 1000) {
            //超过达成时间
            return false;
        }
        if (adDataInfoMap == null || adDataInfoMap.isEmpty()) {
            return false;
        }
        int checkResult = 0;
        int checkCount = 0;
        if (ruleItem.ipu > 0) {
            checkCount += 1;
            if (TextUtils.isEmpty(ruleItem.ipuType)) {
                ruleItem.ipuType = "all";
            }
        }
        if (ruleItem.ecpm > 0) {
            checkCount += 1;
            if (TextUtils.isEmpty(ruleItem.ecpmType)) {
                ruleItem.ecpmType = "all";
            }
        }

        if (ruleItem.ecpmAvg > 0) {
            checkCount += 1;
            if (TextUtils.isEmpty(ruleItem.ecpmAvgType)) {
                ruleItem.ecpmAvgType = "all";
            }
        }
        if (ruleItem.ltv > 0) {
            checkCount += 1;
            if (TextUtils.isEmpty(ruleItem.ltvType)) {
                ruleItem.ltvType = "all";
            }
        }

        //第一步检查ipu
        if (ruleItem.ipu > 0) {
            int type = getAdTypeByRuleType(ruleItem.ipuType);

            AdDataInfo adDataInfo = adDataInfoMap.get(type);
            if (adDataInfo != null && adDataInfo.ipu >= ruleItem.ipu) {
                checkResult += 1;
            }
//            if (type == TYPE_AD_ALL) {
//                int ipu = 0;
//                for (Map.Entry<Integer, AdDataInfo> entry : adDataInfoMap.entrySet()) {
//                    ipu += entry.getValue().ipu;
//                }
//                if (ipu >= ruleItem.ipu) {
//                    checkResult += 1;
//                }
//            } else {
//                AdDataInfo adDataInfo = adDataInfoMap.get(type);
//                if (adDataInfo != null && adDataInfo.ipu >= ruleItem.ipu) {
//                    checkResult += 1;
//                }
//            }
        }

        //第二步检查对应类型是否任意的某一次ecpm是否大于规则里面的标定的值
        if (ruleItem.ecpm > 0) {
            int type = getAdTypeByRuleType(ruleItem.ecpmType);
            AdDataInfo adDataInfo = adDataInfoMap.get(type);
            if (adDataInfo != null) {
                for (Integer value : adDataInfo.ecpmList) {
                    if (value >= ruleItem.ecpm) {
                        checkResult += 1;
                        break;
                    }
                }
            }

//            if (type == TYPE_AD_ALL) {
//                for (Map.Entry<Integer, AdDataInfo> entry : adDataInfoMap.entrySet()) {
//                    for (Integer value : entry.getValue().ecpmList) {
//                        if (value >= ruleItem.ecpm) {
//                            checkResult += 1;
//                            break;
//                        }
//                    }
//                }
//            } else {
//                AdDataInfo adDataInfo = adDataInfoMap.get(type);
//                if (adDataInfo != null) {
//                    for (Integer value : adDataInfo.ecpmList) {
//                        if (value >= ruleItem.ecpm) {
//                            checkResult += 1;
//                            break;
//                        }
//                    }
//                }
//            }
        }

        //第三步检查均值
        if (ruleItem.ecpmAvg > 0) {
            int type = getAdTypeByRuleType(ruleItem.ecpmAvgType);
            AdDataInfo adDataInfo = adDataInfoMap.get(type);
            if (adDataInfo != null && adDataInfo.ipu > 0 && adDataInfo.sumEcpm / adDataInfo.ipu >= ruleItem.ecpmAvg) {
                checkResult += 1;
            }
//
//            if (type == TYPE_AD_ALL) {
//                int sumEcpm = 0;
//                int ipu = 0;
//                for (Map.Entry<Integer, AdDataInfo> entry : adDataInfoMap.entrySet()) {
//                    sumEcpm += entry.getValue().sumEcpm;
//                    ipu += entry.getValue().ipu;
//                }
//                if (ipu > 0 && sumEcpm / ipu >= ruleItem.ecpmAvg) {
//                    checkResult += 1;
//                }
//            } else {
//                AdDataInfo adDataInfo = adDataInfoMap.get(type);
//                if (adDataInfo != null && adDataInfo.ipu > 0 && adDataInfo.sumEcpm / adDataInfo.ipu >= ruleItem.ecpmAvg) {
//                    checkResult += 1;
//                }
//            }
        }

        //第四步检查ltv
        if (ruleItem.ltv > 0) {
            int type = getAdTypeByRuleType(ruleItem.ltvType);
            AdDataInfo adDataInfo = adDataInfoMap.get(type);
            if (adDataInfo != null && adDataInfo.sumEcpm > 0 && adDataInfo.sumEcpm >= ruleItem.ltv) {
                checkResult += 1;
            }

//            if (type == TYPE_AD_ALL) {
//                int sumEcpm = 0;
//                for (Map.Entry<Integer, AdDataInfo> entry : adDataInfoMap.entrySet()) {
//                    sumEcpm += entry.getValue().sumEcpm;
//                }
//                if (sumEcpm > 0 && sumEcpm / 1000 >= ruleItem.ltv) {
//                    checkResult += 1;
//                }
//            } else {
//                AdDataInfo adDataInfo = adDataInfoMap.get(type);
//                if (adDataInfo != null && adDataInfo.sumEcpm > 0 && adDataInfo.sumEcpm / 1000 >= ruleItem.ltv) {
//                    checkResult += 1;
//                }
//            }
        }

        if (checkResult >= checkCount) {
            return true;
        }

        return false;
    }

    //all ints splash native reward
    private static int getAdTypeByRuleType(@NonNull String type) {
        if (TextUtils.isEmpty(type)) {
            return TYPE_AD_ALL;
        }
        if (type.equalsIgnoreCase("splash")) {
            return TYPE_AD_SPLASH;
        } else if (type.equalsIgnoreCase("ints")) {
            return TYPE_AD_INT;
        } else if (type.equalsIgnoreCase("reward")) {
            return TYPE_AD_REWARD;
        } else if (type.equalsIgnoreCase("native")) {
            return TYPE_AD_NATIVE;
        }
        return TYPE_AD_ALL;
    }

/***********************************************************************************/
}
